package com.whf.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created by Administrator on 2018/7/19 0019.
 */
@Component
@ServerEndpoint("/webSocket")
@Slf4j
public class WebSocket {
    private Session session;
    //创建一个存放连接的容器
    private static CopyOnWriteArraySet<WebSocket> webSocketSet=new CopyOnWriteArraySet<>();

    //创建连接时
    @OnOpen
    public void onOpen(Session session){
        this.session=session;
        //将连接放入连接容器中
        webSocketSet.add(this);
        log.info("[websocket消息] 有新的连接,总数:{}",webSocketSet.size());
    }
    //断开连接
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        log.info("[websocket消息] 连接断开,总数:{}",webSocketSet.size());
    }
    //接收到消息时
    @OnMessage
    public void onMessage(String message){
        log.info("[websocket消息]收到客户端发来的消息,message:{}",message);
    }
    public void sendMessage(String message){
        for(WebSocket webSocket:webSocketSet){
            log.info("[websocket消息] 广播消息,message:{}",message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}
